<template>
	<view class="up-order-container">
		<!-- 返回按钮 -->
		<view class="back-btn" @click="goBack">
			<text class="icon">←</text>
			<text>返回</text>
		</view>

		<!-- 页面标题 -->
		<view class="page-title">上传订单</view>

		<!-- 地址选择按钮 -->
		<view class="form-item">
			<text class="label">选择地址<text class="required">*</text></text>
			<view class="address-select-btn" @click="searchAddress">
				<text>{{ selectedLocation.title || '点击选择地址' }}</text>
			</view>
			<text class="selected-address" v-if="selectedLocation.address">
				{{ selectedLocation.address }}
			</text>
			<text class="selected-address" v-if="selectedLocation.name">
				{{ selectedLocation.name }}
			</text>
			<text class="error-message" v-if="showAddressError">请选择地址</text>
		</view>
		<!-- 新增：订单来源单选框 -->
		<view class="form-item">
			<text class="label">订单来源<text class="required">*</text></text>
			<radio-group class="radio-group" @change="radioChange">
				<label class="radio-label" v-for="item in orderSources" :key="item.value">
					<radio :value="item.value" :checked="orderSource === item.value" color="#5c7de8" />
					<text>{{item.name}}</text>
				</label>
			</radio-group>
			<text class="error-message" v-if="showOrderSourceError">请选择订单来源</text>
		</view>
		<view class="form-item">
			<text class="label">订单信息<text class="required">*</text></text>
			<textarea v-model="orderInfo" placeholder="请输入订单信息" class="textarea" />
			<text class="error-message" v-if="showOrderInfoError">请输入订单信息</text>
		</view>
		<!-- 详细地址输入 -->
		<view class="form-item">
			<text class="label">详细地址</text>
			<input v-model="detailAddress" placeholder="请输入楼号/门牌号等详细信息" class="input" />
			<text class="error-message" v-if="showDetailAddressError">请输入详细地址</text>
		</view>

		<!-- 订单信息输入 -->


		<!-- 提交按钮 -->
		<view class="submit-btn" @click="submitOrder">
			提交订单
		</view>
	</view>
</template>

<script>
	import { mapState } from 'vuex' 
	import {
		createOrder
	} from '@/api/new.js'

	export default {
		data() {
			return {
				selectedLocation: { // 选中的位置
					latitude: null,
					longitude: null,
					address: '',
					title: ''
				},
				detailAddress: '', // 详细地址
				orderInfo: '', // 订单信息
				showAddressError: false,
				showDetailAddressError: false,
				showOrderInfoError: false,
				// 新增订单来源相关数据
				orderSource: 'offline', // 当前选中的订单来源
				showOrderSourceError: false, // 是否显示订单来源错误提示
				orderSources: [{
						name: '线下',
						value: 'offline'
					},
					{
						name: '美团',
						value: 'meituan'
					},
					{
						name: '饿了么',
						value: 'eleme'
					},
					{
						name: '抖音',
						value: 'douyin'
					}
				],
			}
		},
		computed: {
			...mapState({
				loginStatus: state => state.user.loginStatus,
				userInfo: state => state.user.userInfo
			})
		},
		methods: {
			// 返回上一页
			goBack() {
				uni.navigateBack()
			},
			// 新增：订单来源变更处理
			radioChange(e) {
				this.orderSource = e.detail.value
				this.showOrderSourceError = false
			},
			// 选择地址
			searchAddress() {
				uni.chooseLocation({
					success: (res) => {
						console.log(res);
						this.selectedLocation = {
							latitude: res.latitude,
							longitude: res.longitude,
							address: res.address,
							title: res.name
						}
						this.showAddressError = false
					},
					fail: () => {
						// 如果用uni.chooseLocation没有获取到地理位置，则需要获取当前的授权信息，判断是否有地理授权信息
						uni.getSetting({
							success: (res) => {
								console.log(res);
								var status = res.authSetting;
								if (!status['scope.userLocation']) {
									// 如果授权信息中没有地理位置的授权，则需要弹窗提示用户需要授权地理信息
									uni.showModal({
										title: "是否授权当前位置",
										content: "需要获取您的地理位置，请确认授权，否则地址选择功能将无法使用",
										success: (tip) => {
											if (tip.confirm) {
												// 如果用户同意授权地理信息，则打开授权设置页面，判断用户的操作
												uni.openSetting({
													success: (data) => {
														// 如果用户授权了地理信息在，则提示授权成功
														if (data
															.authSetting[
																'scope.userLocation'
															] === true
														) {
															uni.showToast({
																title: "授权成功",
																icon: "success",
																duration: 1000
															})
															// 授权成功后，再次调用chooseLocation获取信息
															this
																.searchAddress();
														} else {
															uni.showToast({
																title: "授权失败",
																icon: "none",
																duration: 1000
															})
														}
													}
												})
											}
										}
									})
								}
							},
							fail: (res) => {
								uni.showToast({
									title: "调用授权窗口失败",
									icon: "none",
									duration: 1000
								})
							}
						})
					}
				});
			},

			// 验证表单
			validateForm() {
				let isValid = true

				// 验证地址是否选择
				if (!this.selectedLocation.latitude) {
					this.showAddressError = true
					isValid = false
				} else {
					this.showAddressError = false
				}
				// 新增：验证订单来源
				if (!this.orderSource) {
					this.showOrderSourceError = true
					isValid = false
				} else {
					this.showOrderSourceError = false
				}

				// 验证订单信息
				if (!this.orderInfo.trim()) {
					this.showOrderInfoError = true
					isValid = false
				} else {
					this.showOrderInfoError = false
				}

				return isValid
			},

			// 修改提交订单方法
			    async submitOrder() {
			      // 先验证表单
			      if (!this.validateForm()) {
			        return
			      }
			      
			      try {
			        const fullAddress = `${this.selectedLocation.title}${this.detailAddress}`
			        
					console.log(this.selectedLocation);
					const orderData = {
			          receiverAddress: fullAddress,
			          receiverLongitude: this.selectedLocation.longitude,
					  receiverLatitude: this.selectedLocation.latitude,
			          remark: this.orderInfo,
					  status:1,
					  storeId:this.userInfo.storeId,
			          orderType: 'm-'+this.orderSource // 新增订单来源
			        }
					await createOrder(orderData).then(res => {
			        	console.log(res);
			        })
			        // 调用API提交订单
			        // const res = await createOrder(orderData)
			        
			        uni.showToast({
			          title: '订单提交成功',
			          icon: 'success'
			        })
			        
			        // 提交成功后返回上一页
			        setTimeout(() => {
			          uni.navigateBack()
			        }, 1500)
			        
			      } catch (error) {
			        console.error('提交订单失败:', error)
			        uni.showToast({
			          title: '提交失败，请重试',
			          icon: 'none'
			        })
			      }
			    }
		}
	}
</script>

<style scoped>
	.up-order-container {
		padding: 30rpx;
		position: relative;
	}

	.back-btn {
		display: flex;
		align-items: center;
		margin-bottom: 40rpx;
		color: #007AFF;
		font-size: 30rpx;
	}

	.back-btn .icon {
		margin-right: 10rpx;
		font-size: 36rpx;
	}

	.page-title {
		font-size: 36rpx;
		font-weight: bold;
		margin-bottom: 50rpx;
		text-align: center;
	}

	.form-item {
		margin-bottom: 40rpx;
		position: relative;
	}

	.label {
		display: block;
		margin-bottom: 15rpx;
		font-size: 30rpx;
		color: #333;
	}

	.required {
		color: red;
		margin-left: 5rpx;
	}

	.address-select-btn {
		width: 100%;
		padding: 20rpx;
		border: 1rpx solid #ddd;
		border-radius: 10rpx;
		font-size: 28rpx;
		color: #666;
		background-color: #fff;
	}

	.selected-address {
		display: block;
		margin-top: 10rpx;
		font-size: 24rpx;
		color: #999;
	}

	.input,
	.textarea {
		width: 100%;
		padding: 20rpx;
		border: 1rpx solid #ddd;
		border-radius: 10rpx;
		font-size: 28rpx;
	}

	.textarea {
		height: 200rpx;
	}

	.submit-btn {
		margin-top: 60rpx;
		background-color: #5c7de8;
		color: white;
		text-align: center;
		padding: 25rpx;
		border-radius: 10rpx;
		font-size: 32rpx;
	}

	.submit-btn:active {
		opacity: 0.8;
	}

	.error-message {
		display: block;
		margin-top: 10rpx;
		color: red;
		font-size: 24rpx;
	}
	/* 新增样式 */
	.radio-group {
	  display: flex;
	  flex-wrap: wrap;
	  margin-top: 10rpx;
	}
	
	.radio-label {
	  display: flex;
	  align-items: center;
	  margin-right: 40rpx;
	  margin-bottom: 20rpx;
	  font-size: 28rpx;
	}
</style>